
/**
 * Module dependencies.
 */

var express = require('express');
var fs = require('fs');
var http = require('http');
var path = require('path');
var MongoStore = require('connect-mongo')(express);
var settings = require('./settings')
var flash = require('connect-flash');

var env = process.env.NODE_ENV || 'development'
  , config = require('./config/config')[env]
  , mongoose = require('mongoose');
mongoose.connect(config.db);   //mongoose.connect(config.db, { server: { poolSize: 4 }});

// Bootstrap models
var models_path = __dirname + '/models'
fs.readdirSync(models_path).forEach(function (file) {
  if (~file.indexOf('.js')) require(models_path + '/' + file)
})

var accessLog = fs.createWriteStream('access.log', {flags: 'a'});
var errorLog = fs.createWriteStream('error.log', {flags: 'a'});

var app = express();

var passport = require('passport')
    , GithubStrategy = require('passport-github').Strategy;


// all environments
app.set('port', process.env.PORT || 3100);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(flash());

app.use(express.favicon());

app.use(express.logger({stream: accessLog}));
app.use(express.logger('dev'));
//app.use(express.json());
//app.use(express.urlencoded());
app.use(express.bodyParser());
app.use(express.methodOverride());

app.use(express.cookieParser());
app.use(express.session({
	secret: settings.cookieSecret,
	key: settings.db,   //cookie name
	cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},  //30 days
	store: new MongoStore({
		db: settings.db
	})
}));

//app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(err, req, res, next){
	var meta = '[' + new Date() + ']' + req.url + '\n';
	errorLog.write(meta + err.stack + '\n');
	next();
});

app.use(passport.initialize()); //初始化 Passport

app.use(app.router);

passport.use(new GithubStrategy({
	clientID: config.github.clientID,
	clientSecret: config.github.clientSecret,
	callbackURL: config.github.callbackURL
}, function(accessToken, refreshToken, profile, done){
	//console.log(profile);
	var mongoose = require('mongoose')
      , crypto = require('crypto')
      , User = mongoose.model('User')
    	User.loadByOp({ 'github.id': profile.id }, function (err, user) {
          if (!user) {
            User.loadByOp({username: profile.username}, function(err, localuser){
                if(localuser) return done(err, null);

                var githubUser = new User({
                    username: profile.username,
                    email: profile.emails[0].value,
                    avatar: 'http://www.gravatar.com/avatar/' + crypto.createHash('md5').update(profile.emails[0].value.toLowerCase()).digest('hex') + '?s=48',
                    provider: 'github',
                    github: profile._json
                })
                githubUser.save(function (err) {
                  if (err) console.log(err)
                  return done(err, githubUser)
                })
            });
          } else {
            return done(err, user)
          }
      })
      
}));

// development only
if ('development' == app.get('env')) {
 	app.use(express.errorHandler());
}

// assume 404 since no middleware responded
app.use(function(req, res){
	res.render('404')
})

//routes
var routes = require('./routes')
  , users = require('./routes/users')
  , posts = require('./routes/posts')
  , auth = require('./config/authorization')

//home
app.get('/', routes.index);

//user
app.get('/signup', auth.checkNotLogin, users.signup);
app.post('/signup', auth.checkNotLogin, users.create);
app.get('/signin', auth.checkNotLogin, users.signin);
app.post('/signin', auth.checkNotLogin, users.login);
app.get('/signout', auth.checkLogin, users.signout);

//post

app.get('/posts/new', auth.checkLogin, posts.new);
app.post('/posts', auth.checkLogin, posts.create);
app.get('/posts/search', posts.search);
app.get('/posts/:id', posts.show);
app.get('/posts/:id/edit', auth.checkLogin, posts.edit);
app.put('/posts/:id', auth.checkLogin, posts.update);
app.del('/posts/:id', auth.checkLogin, posts.destroy);



// app.get('/articles', articles.index)
// app.get('/articles/new', auth.requiresLogin, articles.new)
// app.post('/articles', auth.requiresLogin, articles.create)
// app.get('/articles/:id', articles.show)
// app.get('/articles/:id/edit', articleAuth, articles.edit)
// app.put('/articles/:id', articleAuth, articles.update)
// app.del('/articles/:id', articleAuth, articles.destroy)

//archive
app.get('/archive', posts.index);
//tags
app.get('/tags', posts.getTags);
app.get('/tags/:tag', posts.getTag);

app.get('/u/:username', posts.listByUser);

//links
app.get('/links', routes.links);

//reprint
app.get('/posts/reprint/:id', auth.checkLogin, posts.reprint);

//github login
app.get('/auth/github', passport.authenticate('github', {session: false}));
app.get('/auth/github/callback', passport.authenticate('github', {
	session: false,
	failureRedirect: '/signin',
	successFlash: '登陆成功！'
}), users.authCallback);


http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
